package main

import (
	"fmt"
	"my_code/biligoo/other"
	"os"
	"strconv"

	"github.com/valyala/fastjson"
)

var theGiftNum int

//var giftList []string = []string{"浪漫城堡", "荣光之炬", "焰皇神碑", "龙啸之炎", "荣誉之焰", "棉花糖", "焰心火石", "BW舞台", "时空之站", "BW权杖", "BW蛋糕", "电影票"}

func listHave(gift string) bool {
	giftList := TomlInfo.GiftList
	for _, v := range giftList {
		if v == gift {
			return true
		}
	}
	return false
}
func danmuBufRead(buf []byte, bdanmu *biDanmu) (oldbyte []byte) {
	for {
		if len(buf) < 8 {
			oldbyte = buf
			break
		}
		packetLength := int(buf[3]) + int(buf[2])*256 + int(buf[1])*256*256 + int(buf[0])*256*256*256
		if len(buf) < packetLength {
			oldbyte = buf
			break
		}
		headerLength := int(buf[5]) + int(buf[4])*256
		version := int(buf[7]) + int(buf[6])*256
		if buf[11] == 8 {
			fmt.Print(other.TI()+"房间", bdanmu.roomid, " 弹幕连接成功    ")
		}
		msg := buf[headerLength:packetLength]
		if version == 3 {
			msg, _ = DoBrotliCompress(msg)
			oldbyte = danmuBufRead(msg, bdanmu)
			if len(oldbyte) != 0 {
				fmt.Println("解压包后不全")
				os.Exit(0)
			}
		} else if version == 2 {
			msg, _ = DoZlibUnCompress(msg)
			oldbyte = danmuBufRead(msg, bdanmu)
			if len(oldbyte) != 0 {
				fmt.Println("解压包后不全")
				os.Exit(0)
			}
		} else if version == 0 {
			msg = buf[headerLength:packetLength]
			//fmt.Println("buf[11]:", buf[11])
			//fmt.Println("\nMSG:", string(msg))
			danmuMsg(msg, bdanmu)
			//fmt.Println("\nMSG:", string(msg))
		}
		//fmt.Println(version, msg)
		if len(buf) == packetLength {
			oldbyte = []byte{}
			break
		} else {
			buf = buf[packetLength:]
		}
	}
	return
}

func danmuMsg(msg []byte, bdanmu *biDanmu) {
	//fmt.Println(string(msg))
	if len(msg) <= 5 {
		return
	}

	if bdanmu.roomid == 7117440 {
		fmt.Println("\rMSG:", string(msg))
	}
	p := fastjson.Parser{}
	js, err := p.ParseBytes(msg)
	if err != nil {
		fmt.Printf("ParseJson: %v %v\n", err, len(msg))
		return
	}
	if !js.Exists("cmd") {
		//fmt.Println(string(msg))
		return
	}
	cmd := string(js.GetStringBytes("cmd"))
	switch cmd {
	case "ANCHOR_LOT_START":
		if !TomlInfo.POST.Anchor {
			break
		}

		id := js.Get("data", "id").String()
		price := js.GetInt("data", "gift_price") * js.GetInt("data", "gift_num")
		start := js.GetInt("data", "current_time") + js.GetInt("data", "time") - js.GetInt("data", "max_time")

		awardName := string(js.GetStringBytes("data", "award_name"))
		RequireType := js.GetInt("data", "require_type")
		RequireValue := js.GetInt("data", "require_value")
		fmt.Printf("%v天选时刻-%v  房间: %v (%v: %v-%v-%v)        \n", other.TI(), id, bdanmu.roomid, awardName, RequireType, RequireValue, price)

		iid, _ := strconv.Atoi(id)
		rI := getRoomidInfo(bdanmu.roomid)
		uid, uname, face, official_type, official_desc := rI.UID, rI.Uname, rI.Face, rI.OfficialType, rI.OfficialDesc
		awardNum, awardType := js.GetInt("data", "award_num"), js.GetInt("data", "award_type")
		maxTime := js.GetInt("data", "max_time")
		giftRoomAdd(bdanmu.roomid, start+maxTime)
		//fmt.Println(bdanmu.roomid, iid, awardName, RequireType, RequireValue, price, start, maxTime, bdanmu.online, uid, uname, face, official_type, official_desc, awardNum, awardType)
		go postAnchor(bdanmu.roomid, iid, awardName, RequireType, RequireValue, price, start, maxTime, bdanmu.online, uid, uname, face, official_type, official_desc, awardNum, awardType)

	case "SPECIAL_GIFT":
		if !TomlInfo.POST.Storm {
			break
		}
		if string(js.GetStringBytes("data", "39", "action")) != "start" {
			break
		}
		id := js.Get("data", "39", "id").String()
		iid, _ := strconv.ParseInt(id, 10, 64)
		fmt.Printf("%v节奏风暴-%v  房间: %v        \n", other.TI(), id, bdanmu.roomid)
		rI := getRoomidInfo(bdanmu.roomid)
		uid, uname, face, official_type, official_desc := rI.UID, rI.Uname, rI.Face, rI.OfficialType, rI.OfficialDesc
		sTime := js.GetInt("data", "39", "time")
		giftRoomAdd(bdanmu.roomid, int(nowTime())+sTime)
		//fmt.Println(bdanmu.roomid, iid, 0, sTime, bdanmu.online, uid, uname, face, official_type, official_desc)
		go postStorm(bdanmu.roomid, iid, 0, sTime, bdanmu.online, uid, uname, face, official_type, official_desc)

	case "POPULARITY_RED_POCKET_V2_START":
		if !TomlInfo.POST.PopRed {
			break
		}
		price := js.GetInt("data", "total_price")
		rp_type := js.GetInt("data", "rp_type")
		start := js.GetInt("data", "start_time")
		end := js.GetInt("data", "end_time")
		LotID := js.GetInt("data", "lot_id")
		fmt.Printf("%v人气红包V%v-%v  房间: %v (￥%v.%v)        \n", other.TI(), rp_type, LotID, bdanmu.roomid, price/1000, (price-price/1000*1000)/100)
		//fmt.Println(getRoomidInfo(bdanmu.roomid))
		rI := getRoomidInfo(bdanmu.roomid)
		uid, uname, face, official_type, official_desc := rI.UID, rI.Uname, rI.Face, rI.OfficialType, rI.OfficialDesc
		giftRoomAdd(bdanmu.roomid, end)
		//fmt.Println(bdanmu.roomid, LotID, price, start, end-start, bdanmu.online, uid, uname, face, official_type, official_desc)
		go postPopRed(bdanmu.roomid, LotID, price, start, end-start, bdanmu.online, uid, uname, face, official_type, official_desc, rp_type)

	case "RED_POCKET_START":
		if TomlInfo.POST.Red {
			break
		}
		id := js.Get("data", "id").String()
		iid, _ := strconv.ParseInt(id, 10, 64)
		fmt.Printf("%v电池红包-%v  房间: %v        \n", other.TI(), id, bdanmu.roomid)
		rI := getRoomidInfo(bdanmu.roomid)
		uid, uname, face, official_type, official_desc := rI.UID, rI.Uname, rI.Face, rI.OfficialType, rI.OfficialDesc

		giftRoomAdd(bdanmu.roomid, int(nowTime())+js.GetInt("data", "remain_time"))
		//fmt.Println(bdanmu.roomid, iid, 0, js.GetInt("data", "remain_time"), bdanmu.online, uid, uname, face, official_type, official_desc)
		go postRed(bdanmu.roomid, iid, 0, js.GetInt("data", "remain_time"), bdanmu.online, uid, uname, face, official_type, official_desc)

	case "SEND_GIFT": //case "SEND_GIFT": //{"cmd":"SEND_GIFT","data":{"action":"投喂","bag_gift":null,"batch_combo_id":"","batch_combo_send":null,"beatId":"","biz_source":"live","blind_gift":null,"broadcast_id":0,"coin_type":"silver","combo_resources_id":1,"combo_send":null,"combo_stay_time":5,"combo_total_coin":0,"crit_prob":0,"demarcation":1,"discount_price":0,"dmscore":4,"draw":0,"effect":0,"effect_block":1,"face":"https://i2.hdslb.com/bfs/face/71b58aae45d3a88087aa860f53b948f15ca7cb6a.jpg","face_effect_id":0,"face_effect_type":0,"float_sc_resource_id":0,"giftId":1,"giftName":"辣条","giftType":5,"gift_tag":null,"gold":0,"guard_level":0,"is_first":true,"is_join_receiver":false,"is_naming":false,"is_special_batch":0,"magnification":1,"medal_info":{"anchor_roomid":0,"anchor_uname":"","guard_level":0,"icon_id":0,"is_lighted":0,"medal_color":13081892,"medal_color_border":12632256,"medal_color_end":12632256,"medal_color_start":12632256,"medal_level":19,"medal_name":"缠绵","special":"","target_id":475373485},"name_color":"","num":1,"original_gift_name":"","price":100,"rcost":257885131,"receive_user_info":{"uid":11153765,"uname":"3号直播间"},"remain":149,"rnd":"4439684446488205824","send_master":null,"silver":0,"super":0,"super_batch_gift_num":0,"super_gift_num":0,"svga_block":0,"switch":true,"tag_image":"","tid":"4439684446488205824","timestamp":1699447688,"top_list":null,"total_coin":100,"uid":0,"uname":"大***","wealth_level":0}} //ROOM: 23058
		// {"cmd":"SEND_GIFT","data":{"action":"投喂","bag_gift":null,"batch_combo_id":"ff495d48-1f97-4c89-8fd3-46248ff2e8d9","batch_combo_send":{"action":"投喂","batch_combo_id":"ff495d48-1f97-4c89-8fd3-46248ff2e8d9","batch_combo_num":1,"blind_gift":{"blind_gift_config_id":51,"from":0,"gift_action":"爆出","gift_tip_price":9000,"original_gift_id":32251,"original_gift_name":"心动盲盒","original_gift_price":15000},"gift_id":32126,"gift_name":"棉花糖","gift_num":1,"send_master":null,"uid":0,"uname":"哈***"},"beatId":"","biz_source":"live","blind_gift":{"blind_gift_config_id":51,"from":0,"gift_action":"爆出","gift_tip_price":9000,"original_gift_id":32251,"original_gift_name":"心动盲盒","original_gift_price":15000},"broadcast_id":0,"coin_type":"gold","combo_resources_id":1,"combo_send":{"action":"投喂","combo_id":"67057e7b-6f86-4dba-8442-9cc789d81c5c","combo_num":1,"gift_id":32126,"gift_name":"棉花糖","gift_num":1,"send_master":null,"uid":0,"uname":"哈***"},"combo_stay_time":5,"combo_total_coin":9000,"crit_prob":0,"demarcation":2,"discount_price":9000,"dmscore":56,"draw":0,"effect":0,"effect_block":0,"face":"https://i0.hdslb.com/bfs/face/4404cc826e5def0b22dffa29954f296a0542cdb6.jpg","face_effect_id":0,"face_effect_type":0,"float_sc_resource_id":0,"giftId":32126,"giftName":"棉花糖","giftType":0,"gift_tag":[],"gold":0,"group_medal":null,"guard_level":1,"is_first":true,"is_join_receiver":false,"is_naming":false,"is_special_batch":0,"magnification":1,"medal_info":{"anchor_roomid":0,"anchor_uname":"","guard_level":1,"icon_id":0,"is_lighted":1,"medal_color":2951253,"medal_color_border":16771156,"medal_color_end":10329087,"medal_color_start":2951253,"medal_level":30,"medal_name":"凰涩","special":"","target_id":2156921},"name_color":"#FF7C28","num":1,"original_gift_name":"","price":9000,"rcost":69603320,"receive_user_info":{"uid":2156921,"uname":"狱凰阿巴阿巴"},"receiver_uinfo":{"base":{"face":"https://i2.hdslb.com/bfs/face/53fe2efb7fecd07217f5f8ae94094435eed07cf1.jpg","is_mystery":false,"name":"狱凰阿巴阿巴","name_color":0,"name_color_str":"","official_info":{"desc":"","role":0,"title":"","type":-1},"origin_info":{"face":"https://i2.hdslb.com/bfs/face/53fe2efb7fecd07217f5f8ae94094435eed07cf1.jpg","name":"狱凰阿巴阿巴"},"risk_ctrl_info":{"face":"https://i2.hdslb.com/bfs/face/53fe2efb7fecd07217f5f8ae94094435eed07cf1.jpg","name":"狱凰阿巴阿巴"}},"guard":null,"guard_leader":null,"medal":null,"title":null,"uhead_frame":null,"uid":2156921,"wealth":null},"remain":0,"rnd":"4511409193038701568","send_master":null,"sender_uinfo":{"base":{"face":"https://i0.hdslb.com/bfs/face/4404cc826e5def0b22dffa29954f296a0542cdb6.jpg","is_mystery":false,"name":"哈里_马奎尔","name_color":0,"name_color_str":"","official_info":{"desc":"","role":0,"title":"","type":-1},"origin_info":{"face":"https://i0.hdslb.com/bfs/face/4404cc826e5def0b22dffa29954f296a0542cdb6.jpg","name":"哈里_马奎尔"},"risk_ctrl_info":{"face":"https://i0.hdslb.com/bfs/face/4404cc826e5def0b22dffa29954f296a0542cdb6.jpg","name":"哈里_马奎尔"}},"guard":null,"guard_leader":null,"medal":null,"title":null,"uhead_frame":null,"uid":265739403,"wealth":null},"silver":0,"super":0,"super_batch_gift_num":1,"super_gift_num":1,"svga_block":0,"switch":true,"tag_image":"","tid":"4511409193038701568","timestamp":1716548200,"top_list":null,"total_coin":15000,"uid":0,"uname":"哈***","wealth_level":44}}
		uname := string(js.GetStringBytes("data", "uname"))
		// giftName := string(js.GetStringBytes("data", "giftName"))
		// num := js.GetInt("data", "num")
		// if listHave(giftName) {
		// 	theGiftNum += num
		// 	go postRoomGift(bdanmu.roomid, uname, giftName, num, "")
		// 	fmt.Printf("%v%v 赠送了 %vX%v\n心动盲盒 总计: %v  ", other.TI(), uname, giftName, num, theGiftNum)
		// 	fmt.Println(string(msg))
		// }

		original_gift_name := string(js.GetStringBytes("data", "batch_combo_send", "blind_gift", "original_gift_name"))
		if original_gift_name == "心动盲盒" {
			gift_name := string(js.GetStringBytes("data", "batch_combo_send", "gift_name"))
			gift_num := js.GetInt("data", "batch_combo_send", "gift_num")
			batch_combo_id := string(js.GetStringBytes("data", "batch_combo_send", "batch_combo_id"))
			go postRoomGift(bdanmu.roomid, uname, gift_name, gift_num, batch_combo_id)
			//fmt.Printf("%v%v 赠送了 %vX%v\n ", other.TI(), uname, gift_name, gift_num)

		}

	case "DANMU_AGGREGATION":
		activity_identity := js.GetStringBytes("data", "activity_identity")
		aggregation_num := js.GetInt("data", "aggregation_num")
		//fmt.Println(string(activity_identity), aggregation_num)
		go postAttended(string(activity_identity), aggregation_num)

	case "DANMU_MSG":
		uidd := js.GetInt("info", "2", "0")
		ty := js.GetInt("info", "0", "9")
		if ty == 2 {
			if UID != 0 && UID == uidd {
				fmt.Printf("%v用户 在房间%v 人气红包 真·参与成功 \n", other.TI(), bdanmu.roomid)
			}
		}
		uname := string(js.GetStringBytes("info", "2", "1"))
		umsg := string(js.GetStringBytes("info", "1"))
		if uidd == 146563374 {
			fmt.Printf("%v房间%v %v: %v   \n", other.TI(), bdanmu.roomid, uname, umsg)
		}
		//fmt.Printf("\r%v: %v %v: %v    \n", bdanmu.roomid, uidd, uname, umsg)

	case "ONLINE_RANK_COUNT":
		count := js.GetInt("data", "count")
		if bdanmu.online != count {
			bdanmu.online = count
			if giftRoomHave(bdanmu.roomid) {
				go postOnline(bdanmu.roomid, count)
			}
		}
	case "INTERACT_WORD": //{"cmd":"INTERACT_WORD","data":{"contribution":{"grade":0},"contribution_v2":{"grade":0,"rank_type":"","text":""},"core_user_type":0,"dmscore":44,"fans_medal":{"anchor_roomid":27167292,"guard_level":3,"icon_id":0,"is_lighted":1,"medal_color":398668,"medal_color_border":6809855,"medal_color_end":6850801,"medal_color_start":398668,"medal_level":25,"medal_name":"去了","score":50016647,"special":"","target_id":3493137320249900},"group_medal":null,"identities":[3,1],"is_mystery":false,"is_spread":0,"msg_type":1,"privilege_type":0,"roomid":47867,"score":1764437342765,"spread_desc":"","spread_info":"","tail_icon":0,"tail_text":"","timestamp":1714410695,"trigger_time":1714410694571624400,"uid":130492,"uinfo":{"base":{"face":"https://i1.hdslb.com/bfs/face/a54516e77eba05cdca884255efee9f27e4d32535.jpg","is_mystery":false,"name":"灼热之痕","name_color":0,"name_color_str":"","official_info":null,"origin_info":null,"risk_ctrl_info":null},"guard":{"expired_str":"","level":0},"guard_leader":null,"medal":{"color":398668,"color_border":6809855,"color_end":6850801,"color_start":398668,"guard_icon":"","guard_level":3,"honor_icon":"","id":0,"is_light":1,"level":25,"name":"去了","ruid":3493137320249900,"score":50016647,"typ":0},"title":null,"uhead_frame":null,"uid":130492,"wealth":{"dm_icon_key":"","level":32}},"uname":"灼热之痕","uname_color":""}} //ROOM: 47867
		uid := js.GetInt("data", "uid")
		uname := js.GetInt("data", "uname")
		if uid == 1 {
			fmt.Printf("%v%v进入房间%v  \n", other.TI(), uname, bdanmu.roomid)

		}
	default:
		cmdlock.Lock()
		if _, ok := cmdmap[cmd]; !ok {
			cmdmap[cmd] = string(msg)

			a := fmt.Sprintf("case \"%v\": //%v //ROOM: %v\n", cmd, string(msg), bdanmu.roomid)
			printLogFile(a)
			//fmt.Println(a)
		}
		cmdlock.Unlock()
	}
}
